<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input
            size="small"
            v-model="queryinfo.query"
            placeholder="请输入内容"
            class="input-with-select"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="query()"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" size="small" @click="gosave()"
            >添加</el-button
          >
        </el-col>
      </el-row>

      <el-row>
        <el-table class="tabletop" :data="tableData" border style="width: 100%">
          <el-table-column label="序号" type="index"></el-table-column>
          <el-table-column
            prop="username"
            label="用户名"
            width="180"
          ></el-table-column>
          <el-table-column prop="email" label="邮箱地址"></el-table-column>
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                @change="changeUserState(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="198">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="goeait(scope.row)"
              ></el-button>
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="del(scope.row)"
              ></el-button>
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-s-tools"
                @click="gosetrole(scope.row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryinfo.pagenum"
          :page-sizes="[2, 4, 6, 8]"
          :page-size="queryinfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalnum"
        ></el-pagination>
      </el-row>
    </el-card>
    <el-dialog title="用户维护" :visible.sync="isShow">
      <el-form
        :model="saveobj"
        :rules="checkobj"
        ref="saveform"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="账号" prop="username">
          <el-input :disabled="iseait" v-model="saveobj.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!iseait">
          <el-input v-model="saveobj.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="saveobj.email"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="mobile">
          <el-input v-model="saveobj.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="save()">确 定</el-button>
      </div>
    </el-dialog>


<el-dialog title="分配角色" :visible.sync="roleShow" :close-on-click-modal="false">
  <el-form :model="setroleobj">
    <el-form-item label="用户名:">
       {{setroleobj.username}}
    </el-form-item>
        <el-form-item label="当前角色:">
       {{setroleobj.role_name}}
    </el-form-item>
    <el-form-item label="活动区域">
      <el-select v-model="setroleobj.rid" placeholder="请选择角色">
        <el-option v-for="(item) in rolelist" :label="item.roleName" :value="item.id" :key="item.id"></el-option>
      </el-select>
    </el-form-item>
  </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="setrole()">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "users",
  data() {
    const checkemail = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入邮箱"));
      } else {
        callback();
      }
    };
    return {
      queryinfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      totalnum: 0,
      tableData: [],
      rolelist:[],
      isShow: false,
      saveobj: {
        id: 0,
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      setroleobj:{
        id:0,
        rid:"",
        role_name:"",
        username:""
      },
      roleShow:false,
      checkobj: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 4, max: 12, message: "长度在4-12之间", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        email: [{ validator: checkemail, trigger: "blur" }],
        mobile: [
          { required: true, message: "请输入联系方式", trigger: "blur" },
        ],
      },
      iseait: false,
    };
  },
  methods: {
    //查，显示数据
    async query() {
      let rst = await this.$http.get("users", this.queryinfo);
      if (rst.meta.status == 200) {
        this.tableData = rst.data.users;
        this.totalnum = rst.data.total;
      } else {
        this.$message.error("服务器繁忙");
      }
      console.log(rst);
    },

    //点击修改
    async goeait(obj) {
      let rst = await this.$http.get(`users/${obj.id}`);
      if (rst.meta.status == 200) {
        console.log(rst);
        this.saveobj.id = rst.data.id;
        this.saveobj.username = rst.data.username;
        this.saveobj.mobile = rst.data.mobile;
        this.saveobj.email = rst.data.email;
        this.isShow = true;
        this.iseait = true;
      } else {
        this.$message.error("获取数据失败");
      }
    },
    //点击删除
    del(obj) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let rst = await this.$http.delete(`users/${obj.id}`);
          if (rst.meta.status == 200) {
            this.query();
          } else {
            this.$message.error("删除失败");
          }
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    //点击保存/修改确认
    save() {
      this.$refs.saveform.validate(async (valid) => {
        if (valid) {
          let rst = null;
          if (this.saveobj.id != 0) {
            rst = await this.$http.put(
              `users/${this.saveobj.id}`,
              this.saveobj
            );
          } else {
            rst = await this.$http.post("users", this.saveobj);
          }
          if (rst.meta.status == 201 || rst.meta.status == 200) {
            this.$message.success("保存成功");
            this.isShow = false;
            this.query();
          } else {
            this.$message.error("添加失败");
          }
        } else {
          this.$message.error("请完善所有输入的信息");
          return;
        }
      })
    },
    gosave() {
      this.isShow=true;
      this.iseait=false;
      this.saveobj={
        id: 0,
        username:"",
        password:"",
        email:"",
        mobile:"",
      }
    },
    handleSizeChange(size){
      this.queryinfo.pagesize=size;
      this.query();
    },
    handleCurrentChange(pagenum){
      this.queryinfo.pagenum=pagenum;
      this.query();
    },
    async changeUserState(obj){
      let rst=await this.$http.put(`users/${obj.id}/state/${obj.mg_state}`);
      if (rst.meta.status!=200) {
        this.$message.error("状态修改失败");
      }
    },
    async getrolelist(){
      let rst=await this.$http.get("roles");
      if(rst.meta.status==200){
        this.rolelist=rst.data;
      }
      else{
        this.$message.error("获取角色失败")
      }
    },
    gosetrole(obj){
    let {id,role_name,username}=obj;
    this.setroleobj.role_name=role_name;
    this.setroleobj.username = username;
    this.setroleobj.id=id;
    this.roleShow=true;
  },
  async setrole(){
    if(this.setroleobj.rid){
      let rst=await this.$http.put(`users/${this.setroleobj.id}/role`,{rid:this.setroleobj.rid})
      console.log(rst);
      if(rst.meta.status==200){
        this.query();
        this.roleShow=false;
        this.$message.success("角色分配成功");
      }
      else{
        this.$message.error("角色分配失败");
      }
      
    }
    else{
        this.$message.error("请选择新的角色");
    }
  }
  },
  mounted(){
    this.query();
    this.getrolelist();
  }
};
</script>

<style>
.box-card {
  margin-top: 20px;
}
.mbbottom {
  margin-bottom: 20px;
}
.tabletop {
  margin-top: 20px;
}
</style>